package com.chukun.spring.dependency.injection;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import javax.annotation.Resource;

/**
 * 基于 字段 方式注入示例
 * @author chukun
 */
public class AnnotationDependencyFieldInjectionDemo {

    /**
     * 基于字段的注入 static字段与方法会忽略
     */
    @Autowired
    private  UserHolder userHolder;

    @Resource
    private UserHolder userHolder2;

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        applicationContext.register(AnnotationDependencyFieldInjectionDemo.class);

        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);

        String location = "classpath:/META-INF/dependency-lookup-context.xml";
        // 加载BeanDefinition
        reader.loadBeanDefinitions(location);

        // 启动 Spring 应用上下文
        applicationContext.refresh();

        // 依赖查找
        AnnotationDependencyFieldInjectionDemo dependencyFieldInjectionDemo = applicationContext.getBean(AnnotationDependencyFieldInjectionDemo.class);
        System.out.println(dependencyFieldInjectionDemo.userHolder);

        System.out.println(dependencyFieldInjectionDemo.userHolder2);

        // 这两个注入的对象是同一个
        System.out.println(dependencyFieldInjectionDemo.userHolder == dependencyFieldInjectionDemo.userHolder2);

        // 显示地关闭 Spring 应用上下文
        applicationContext.close();

    }

    @Bean
    public UserHolder userHolder(User user) {
        return new UserHolder(user);
    }
}
